package com.lz.yz.security;


import com.lz.yz.base.exception.UnauthorizedException;
import com.lz.yz.member.entity.Account;
import com.lz.yz.member.service.AccountService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;

/**
 * 拦截器类, 可以在这里作用户登陆鉴权.
 * 通过 WebMvcConfig 类 注册到 SpringMvc 中.
 */
@Component
public class AuthInterceptor extends HandlerInterceptorAdapter {

    @Autowired
    AccountService accountService;


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String headToken = request.getHeader("Authorization");
        String uri = request.getRequestURI();
        Integer accountId;

        //不进行拦截的请求
        if (uri.contains("/auth/refreshToken") || uri.contains("/user/register")
                || uri.contains("/user/band") || uri.contains("/user/other")
                || uri.contains("/user/oAuthLogin") || uri.contains("/wechat") || uri.contains("/upload")
                || uri.contains("/v2/api-docs") || uri.contains("swagger") || uri.contains("error") || uri.contains("swg") || uri.contains("configuration")
                || uri.contains("/index") || uri.contains("/questionBuff/questionList")
                ) {
            return super.preHandle(request, response, handler);
        }

        if (StringUtils.isBlank(headToken)) {
            throw new UnauthorizedException("你还没有登录，请前往登录");
        }
        if (headToken.length() < 8) {
            throw new UnauthorizedException("token错误");
        }

        String token = headToken.substring("Bearer ".length());
        Account account=accountService.getAccountByToken(token);
        if(account==null){
            throw new UnauthorizedException("权限不足");
        }
        accountId = account.getId();

        if (new Date().after(account.getExpireAt())) {
            throw new UnauthorizedException("认证信息过期，请重新登录！ ");
        }
        //认证成功将用户信息放进request
        request.setAttribute("accountId", accountId);
        request.setAttribute("account", account);
        return super.preHandle(request, response, handler);
    }

}
